import os
import csv
import datetime


def get_file_info(folder_path):
    file_info = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            file_size = os.path.getsize(file_path)

            # 将文件大小转换为可读的单位
            if file_size < 1024:
                size_str = f"{file_size} B"
            elif file_size < 1024 * 1024:
                size_str = f"{file_size / 1024:.3f} KB"
            elif file_size < 1024 * 1024 * 1024:
                size_str = f"{file_size / (1024 * 1024):.3f} MB"
            else:
                size_str = f"{file_size / (1024 * 1024 * 1024):.3f} GB"

            creation_time = os.path.getctime(file_path)
            creation_time = datetime.datetime.fromtimestamp(creation_time).strftime('%Y-%m-%d %H:%M:%S')
            file_info.append((file, size_str, creation_time))
    return file_info


def save_to_csv(file_info, csv_path):
    with open(csv_path, 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['文件名', '文件大小', '创建时间'])
        writer.writerows(file_info)


if __name__ == "__main__":
    folder_path = input("请输入目标文件夹路径：")
    if not os.path.exists(folder_path):
        print("文件夹不存在！")
    else:
        file_info = get_file_info(folder_path)
        # 将 CSV 文件保存到桌面
        desktop_path = os.path.join(os.path.expanduser("~"), 'Desktop')
        csv_path = os.path.join(desktop_path, 'file_info2.csv')
        save_to_csv(file_info, csv_path)
        print(f"文件信息已保存到 {csv_path}")